import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { Phase } from "../../../../entity/phase.model";
import { FormBuilder, Validators, FormControl } from "@angular/forms";
import { PhaseService } from "../../../../service/phase.service";
import { FarmService } from "../../../../service/farm.service";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";
import { Farm } from "../../../../entity/farm.model";
import { DatePipe } from "@angular/common";
@Component({
    selector: 'app-phase-edit',
    templateUrl: './phase-edit.component.html',
    styleUrls: ['./phase-edit.component.css']
})
export class PhaseEditComponent extends BladeContainerBase<Phase>{
    farms: Farm[] = [];
    constructor(
        private datePipe: DatePipe,
        private fb: FormBuilder,
        private phaseService: PhaseService,
        private farmService: FarmService) {
        super(fb);
    }

    ngOnInit(): void {
        //编辑时注册按钮和按钮命令    
        if (!this.isNew) {
            this.commands = [
                new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
                new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
            ]
        }
        else {
            this.currentEntity = new Phase(0, 0, "", "", 0, new Date().toString(), 0);
        }
        super.ngOnInit();   
    }

    /**
     * 初始化数据
     * 
     * 
     * @memberof BladeContainerBase
     */
    initData(): any | Observable<any> | Promise<any> {
        this.farmService.getFarms()
            .then(res => {
                this.farms = [...res];                
                if (this.isNew) {
                    if (this.parentBlade.parentEntity != null)
                        this.currentEntity.farmId = (this.parentBlade.parentEntity as Farm).farmId;
                    else {
                        if (this.farms.length > 0)
                            this.currentEntity.farmId = this.farms[0].farmId;
                    }
                }
                this.formPatchValue(this.currentEntity);

            })
            .catch(error => this.bladeData.error = error)
            .then(res => this.bladeData.isLoading = false);

    }

    exeSaveChange(blade: any): void {
        this.saveChange();
    }
    canSaveChange(blade: any): boolean {
        return this.hasChange() && !this.hasError();
    }
    exeReset(blade: any): void {
        return this.formGroup.reset(this.currentEntity);
    }
    canReset(blade: any): boolean {
        return this.hasChange();
    }

    /**
   * 创建表单
   * 
   * 
   * @memberof DicKeyEditComponent
   */
    createForm() {

        this.formGroup = this.fromBuider.group({
            "farmId": [this.currentEntity.farmId, [
                Validators.required,
                Validators.pattern("[0-9]{1,5}"),
                Validators.maxLength(5),
            ]],
            "phaseId": [this.currentEntity.phaseId, [
                Validators.required,
                Validators.pattern("[0-9]{1,20}"),
                Validators.maxLength(20),
            ]],

            "phaseCode": [this.currentEntity.phaseCode, [
                Validators.required,
                //Validators.pattern("[0-9a-zA-Z]{1,20}"),
                Validators.maxLength(20),
            ], (control: FormControl): any => this.phaseCodeAsnyValidator(control)],
            //, (control: FormControl): any => this.farmCodeAsnyValidator(control)
            "phaseName": [this.currentEntity.phaseName, [
                Validators.required,
                // Validators.pattern("[\u4e00-\u9fa5]{1,20}"),
                Validators.maxLength(20),
            ], (control: FormControl): any => this.phaseNameAsnyValidator(control)],
            //, (control: FormControl): any => this.farmNameAsnyValidator(control)

            "capacity": [this.currentEntity.capacity, [//??????????????????????
                Validators.required,
                Validators.maxLength(7),
            ]],
            "productionDate": [this.currentEntity.productionDate, [//????????????
                //Validators.required,
                //Validators.pattern("([0-9]{4})[-,/]([0-9]{2})[-,/]([0-9]{2})"),
                //Validators.maxLength(20),
            ]],

            "phaseSeq": [this.currentEntity.phaseSeq, [
                Validators.required,
                Validators.pattern("^([0-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"),
                Validators.maxLength(5)
            ]]

        });
    }

    /**
   * 设置表单错误对象
   * 
   * 
   * @memberof BladeContainerBase
   */
    setFormError(): void {
        this.formErrors = {
            'phaseId': '',
            'farmId': '',
            'phaseCode': '',
            'phaseName': '',
            'capacity': '',
            'productionDate': '',
            'phaseSeq': ''
        };
    }
    /**
    * 设置表单验证信息
    * 
    * 
    * @memberof BladeContainerBase
    */
    setValidationMessages(): void {
        this.validationMessages = {
            'phaseId': {
                'required': '不能为空。',
                'pattern': '由数字组成。',
                'maxlength': '不能多于20个字符长度。',
                'exist': '已存在。',
            },
            'farmId': {
                'required': '不能为空。',
                'pattern': '由数字组成。',
                'maxlength': '不能多于20个字符长度。',
                'exist': '已存在。',
            },
            'phaseCode': {
                'required': '不能为空。',
                'pattern': '由英文、数字组成。',
                'maxlength': '不能多于20个字符长度。',
                'exist': '已存在。',
            },
            'phaseName': {
                'required': '不能为空。',
                'pattern': '由汉子组成。',
                'maxlength': '不能多于20个字符长度。',
                'exist': '已存在。',
            },
            'capacity': {
                'required': '不能为空。',
                'pattern': '由数字组成。',
                'maxlength': '不能多于7个字符长度。',
                'exist': '已存在。',
            },
            'productionDate': {
                'required': '不能为空。',

            },
            'phaseSeq': {
                'required': '不能为空。',
                'rang': '范围是0~255。',
                'maxlength': '不能多于5个字符长度。'
            }

        };
    }
    /**
     * 异步校验phaseCode是否存在
     */
    phaseCodeAsnyValidator(control: FormControl): any {
       
        if (!control.value || control.value == this.currentEntity.phaseCode) {
            return Observable.of(null);
        }       
        return this.phaseService.hasPhaseCode(control.value, this.currentEntity.farmId, this.currentEntity.phaseId)
            .map(res => res ? { exist: true } : null);
    }


    /**
    * 异步校验phaseName是否存在
    */
    phaseNameAsnyValidator(control: FormControl): any {
        if (!control.value || control.value == this.currentEntity.phaseName) {
            return Observable.of(null);
        }
        return this.phaseService.hasPhaseName(control.value, this.currentEntity.farmId, this.currentEntity.phaseId)
            .map(res => res ? { exist: true } : null);
    }

    onCreate() {
        if (!this.hasError()) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value;
            this.currentEntity.phaseId = formValue.phaseId;
            this.currentEntity.farmId = formValue.farmId;
            this.currentEntity.phaseCode = formValue.phaseCode;
            this.currentEntity.phaseName = formValue.phaseName;
            this.currentEntity.capacity = formValue.capacity;
            this.currentEntity.productionDate =this.datePipe.transform(formValue.productionDate,"yyyy-MM-dd").toString();
            this.currentEntity.phaseSeq = formValue.phaseSeq;
            this.phaseService.create(this.currentEntity)
                .then(res => {
                    if (res) {
                        let parentContainerInstance = this.parentBlade.bladeContainerInstance;
                        parentContainerInstance.refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }

    saveChange(): any | Promise<any> | Observable<any> {
        if (this.canSaveChange(this.currentBlade)) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value;
            this.currentEntity.phaseId = formValue.phaseId;
            this.currentEntity.farmId = formValue.farmId;
            this.currentEntity.phaseCode = formValue.phaseCode;
            this.currentEntity.phaseName = formValue.phaseName;
            this.currentEntity.capacity = formValue.capacity;
            this.currentEntity.productionDate = formValue.productionDate;
            this.currentEntity.phaseSeq = formValue.phaseSeq;

            return this.phaseService.update(this.currentEntity)
                .then(res => {
                    if (res) {
                        (this.parentBlade.bladeContainerInstance).refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }

}



// WEBPACK FOOTER //
// ./src/app/module/basic/phase/phase-edit/phase-edit.component.ts